﻿/*
 * Created by SharpDevelop.
 * User: bcrawford
 * Date: 8/1/2014
 * Time: 8:23 AM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;

namespace RfiCodingService
{
  public class RfiServiceStarter : ServiceBase
  {
    public const string MyServiceName = "Rfi Service Starter";
    
    private System.Diagnostics.EventLog eventLog;
    
    private ServiceController controller;
    
    public RfiServiceStarter()
    {
      InitializeComponent();
    }
    
    private void InitializeComponent()
    {
      this.ServiceName = MyServiceName;
      
      this.eventLog = new EventLog();
      
      this.eventLog.Source = this.ServiceName;
      
      ((System.ComponentModel.ISupportInitialize)(this.eventLog)).BeginInit();
      
      controller = new ServiceController(RfiCoder.RfiCoder.MyServiceName);
    }
    
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose(bool disposing)
    {
      // TODO: Add cleanup code here (if required)
      base.Dispose(disposing);
    }
    
    /// <summary>
    /// Start this service.
    /// </summary>
    protected override void OnStart(string[] args)
    {
      var timeOut = TimeSpan.FromMilliseconds(2000d);
      
      if ( controller.Status == ServiceControllerStatus.Stopped ) {
        this.eventLog.WriteEntry("Starting the RFI coding service", EventLogEntryType.Information);
        
        using ( new RfiCoder.Utilities.Impersonator(
          RfiCoder.Configuration.ConfigHandler.InstanceOf.LogonName,
          "rha",
          RfiCoder.Configuration.ConfigHandler.InstanceOf.LogonPassword) ) {
          controller.Start();
        }
        
        try {
          controller.WaitForStatus(ServiceControllerStatus.Running, timeOut);
        } catch ( System.ServiceProcess.TimeoutException exception ) {
          this.eventLog.WriteEntry("The RFI starter timed out waiting for the rfi coding service to start", EventLogEntryType.Error);
        }
      }
    }
    
    /// <summary>
    /// Stop this service.
    /// </summary>
    protected override void OnStop()
    {
      if ( controller.Status == ServiceControllerStatus.Running ) {
        controller.Stop();
      }
    }
  }
}
